<template>
  <div class="register-page">
    <div class="register">
      <div class="login__title">{{ $t('title') }}</div>
      <div class="login__subtitle">{{ $t('hrRegisterTitle') }}</div>
      <el-form :model="registerForm" :rules="rules" ref="refRegisterForm" size="medium" :label-width="formLabelWidth">
        <el-row>
          <el-col :span="8">
            <el-form-item label="企业名称" prop="enterpriseName">
              <el-input v-model="registerForm.enterpriseName" placeholder="请选择企业名称" readonly="readonly">
                <template #suffix>
                  <el-icon @click="findEnterprise"><Search/></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="registerForm.username" placeholder="请输入用户名" maxlength="64"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="registerForm.name" placeholder="请输入姓名" maxlength="64"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="密码" prop="password">
              <el-input v-model="registerForm.password" placeholder="请输入密码" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="registerForm.contactPhone" placeholder="请输入联系电话" maxlength="64"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="registerForm.email" placeholder="请输入邮箱" maxlength="64"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="确认密码" prop="password">
              <el-input v-model="registerForm.password2" placeholder="请确认密码" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="verificationCode" label="验证码">
              <el-input v-model="registerForm.verificationCode" placeholder="请输入验证码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <canvas id="captchaCanvas" width="150" height="50" @click="drawCaptcha"></canvas>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="center-container">
              <el-button type="primary" @click="onRegister" :loading="loading">注册</el-button>
              <el-button @click="onReset">重置</el-button>
              <el-button type="primary" @click="onBack">返回登录</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="footer">
      <span>版权所有 &copy; 2024 - 2026 <a href="http://www.52ejn.com" target="_blank">源码学习网</a></span><a href="http://beian.miit.gov.cn" target="_blank">粤ICP备2024308896号-1</a>
    </div>
    <el-dialog v-model="enterpriseSelectorVisible" v-if="enterpriseSelectorVisible" title="企业信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth" :append-to-body="true">
      <enterprise-selector @enterprise-selected-event="handleEnterpriseSelectedEvent">
      </enterprise-selector>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {inject, onMounted, reactive, ref, toRefs} from 'vue';
import recruiterApi from '@/api/recruiterApi'
import type {FormInstance} from 'element-plus';
import {ElMessage} from 'element-plus'
import type {HrRegisterForm} from "@/types/req/hrRegisterForm";
import type {Result} from '@/types/result'
import {useCaptcha} from '@/composables/useCaptcha'
import {useRouter} from 'vue-router'
import { Search } from '@element-plus/icons-vue';
import EnterpriseSelector from "@/views/enterprise/EnterpriseSelector.vue";

const { generatedVerificationCode, drawCaptcha } = useCaptcha()

const refRegisterForm = ref<FormInstance | null>(null);
const registerForm = reactive<HrRegisterForm>({
  enterpriseId: 0,
  enterpriseName: '',
  username: '',
  name: '',
  password: '',
  password2: '',
  contactPhone: '',
  email: '',
  verificationCode: ''
})
const enterpriseSelectorVisible = ref<boolean>(false)
const loading = ref<boolean>(false)
const router = useRouter()

const rules = reactive({
  enterpriseName: [
    { required: true, message: '请输入企业名称', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  password2: [
    { required: true, message: '请确认密码', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
});
const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')
const formLabelWidth = ref<string>('')

onMounted(() => {
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string, formLabelWidth?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.formLabelWidth) {
    formLabelWidth.value = globalStateRefs.formLabelWidth.value || ''
  }
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
});

const onReset = () => {
  if (refRegisterForm.value) {
    refRegisterForm.value.resetFields()
  }
}

const refreshCaptcha = () => {
  registerForm.verificationCode = ''
  drawCaptcha()
}

const onRegister = () => {
  if (!refRegisterForm.value) {
    return
  }
  refRegisterForm.value.validate(async (valid: boolean) => {
    if (valid) {
      if (registerForm.password !== registerForm.password2) {
        ElMessage.error('两次输入的密码不一致，请重新输入')
        registerForm.password = ''
        registerForm.password2 = ''
        refreshCaptcha()
        return
      }
      if (generatedVerificationCode.value.toLowerCase() !== registerForm.verificationCode.toLowerCase()) {
        ElMessage.error('验证码错误')
        refreshCaptcha()
        return
      }
      loading.value = true
      const resp: Result<void> = await recruiterApi.save(registerForm)
      if (resp && resp.code === 1) {
        ElMessage.success('注册成功')
        await router.push({ path: '/Login', query: {type: 2} })
      } else {
        ElMessage.error('注册失败:' + (resp.msg ? resp.msg : ''))
        refreshCaptcha()
        loading.value = false
      }
    }
  })
}

const findEnterprise = () => {
  enterpriseSelectorVisible.value = true
}

const handleEnterpriseSelectedEvent = (selectedEnterprise: any) => {
  enterpriseSelectorVisible.value = false
  if (selectedEnterprise && 'enterpriseId' in selectedEnterprise && registerForm.enterpriseId !== selectedEnterprise['enterpriseId']) {
    registerForm.enterpriseId = selectedEnterprise['enterpriseId']
    registerForm.enterpriseName = selectedEnterprise['enterpriseName']
  }
}

const onBack = () => {
  router.push({ path: '/Login', query: {type: 2} })
}

</script>

<style lang="scss">
@use "@/assets/register.scss";
</style>
